package com.booter.webflux.service;

import com.booter.webflux.model.Menu;
import com.booter.webflux.repository.mongo.MenuMongoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.Date;
import java.util.UUID;

@Component
public class MenuFluxHandler {

    @Autowired
    private MenuMongoRepository repository;


    @NonNull
    public Mono<ServerResponse> getMenuList(ServerRequest request) {
        return ServerResponse.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(this.repository.findAll(), Menu.class);
    }

    @NonNull
    public Mono<ServerResponse> save(ServerRequest request) {
        Mono<Menu> menu = request.bodyToMono(Menu.class).flatMap(s -> {
            s.setId(UUID.randomUUID().toString());
            s.setCreateTime(new Date());
            s.setUpdateTime(new Date());
            return Mono.just(s);
        });
        return ServerResponse.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(this.repository.saveAll(menu), Menu.class);
    }

    @NonNull
    public Mono<ServerResponse> delete(ServerRequest request) {
        String id = request.pathVariable("id");
//        return this.repository.findById(id).map(s -> s.getId()).flatMap(this.repository::deleteById)
//                .then(ServerResponse.ok().build())
//                .switchIfEmpty(ServerResponse.notFound().build());

        return this.repository.findById(id).flatMap(s ->
                this.repository.deleteById(s.getId()).then(ServerResponse.ok().build())
        ).switchIfEmpty(ServerResponse.notFound().build())
                //在这只能使用switchIfEmpty ，他的入参是Mono<ServerResponse>
                //defaultIfEmpty 入参是ServerResponse, ServerResponse的实现是非public抽象静态类AbstractServerResponse，无法直接引用
                .flatMap(s -> {
                    if (s.rawStatusCode() == HttpStatus.OK.value()) {
                        return ServerResponse.ok().body(Mono.just("ok"), String.class);
                    } else {
                        return ServerResponse.status(400).body(Mono.just("id[" + id + "] is not fund"), String.class);
                    }
                });


    }

}
